<template>
  <el-dialog title="导入Excel" :visible.sync="open" width="400px" append-to-body>
    <el-upload
      ref="upload"
      :limit="1"
      accept=".xlsx, .xls"
      :action="action"
      :headers="uploadHeaders"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
      :show-file-list="true"
      :data="uploadData"
      :auto-upload="false"
      class="upload-excel"
    >
      <el-button slot="trigger" type="primary">选择文件</el-button>
      <div slot="tip" class="el-upload__tip">只能上传 xls/xlsx 文件</div>
    </el-upload>
    <div slot="footer" class="dialog-footer">
      <el-button type="success" @click="submitUpload">上传</el-button>
      <el-button @click="cancelUpload">取消</el-button>
    </div>
  </el-dialog>
</template>


<script>
export default {
  name: "UploadExcel",
  props: {
    action: {
      type: String,
      required: true
    },
    templateUrl: {
      type: String,
      required: false // 你现在没启用下载按钮
    }
  },
  data() {
    return {
      open: false,
      uploadHeaders: {
        Authorization: "Bearer " + this.$store.getters.token
      },
      uploadData: {}
    }
  },
  methods: {
    openDialog() {
      this.open = true;
    },
    submitUpload() {
      // ✅ 只有点了“上传”按钮才会调用
      this.$refs.upload.submit();
    },
    beforeUpload(file) {
      const extension = file.name.split('.').pop().toLowerCase();
      const isExcel = extension === 'xls' || extension === 'xlsx';
      if (!isExcel) {
        this.$message.error('只能上传 Excel 文件');
      }
      return isExcel;
    },
    handleSuccess(response) {
      this.$emit('success', response);
      this.$message.success(response.msg || '导入成功');
      this.open = false;
      this.$refs.upload.clearFiles(); // ✅ 上传成功后清除选择
    },
    handleError() {
      this.$message.error('导入失败，请检查文件格式和数据');
    },
    cancelUpload() {
      this.open = false;
      this.$refs.upload.clearFiles(); // ✅ 取消时也清空
    }
  }
}

</script>
